package com.csthink.mr.inputformat;

import com.csthink.mr.wordcount.WordCountDriver;
import com.csthink.utils.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * 演示 KeyValueTextInputFormatApp 的使用，可以使用分隔符分割每行的数据进行处理
 *
 * @author <a href="mailto:csthink@icloud.com">Mars</a>
 * @since 2024-04-15 10:10
 */
public class DBInputFormatApp {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        String output = "out";

        Configuration conf = new Configuration();
        DBConfiguration.configureDB(conf,
                "com.mysql.cj.jdbc.Driver",
                "jdbc:mysql://localhost:3306/csthink",
                "root",
                "123456");
        Job job = Job.getInstance(conf);

        FileUtils.deleteIfExists(conf, output);

        job.setJarByClass(DBInputFormatApp.class);

        job.setMapperClass(MyMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(WebPermissionWritable.class);
        job.setInputFormatClass(DBInputFormat.class);

        String[] fields = {"id", "permission", "sub_permission", "display_order"};
        //DBInputFormat.setInput(job, WebPermissionWritable.class,"cst_web_permission",null, null, fields);

        // order by 无效
        String inputQuery = "select id,permission,sub_permission,display_order from cst_web_permission order by id asc";
        String inputCountQuery = "select count(*) from cst_web_permission";
        DBInputFormat.setInput(job, WebPermissionWritable.class, inputQuery, inputCountQuery);

        FileOutputFormat.setOutputPath(job, new Path(output));

        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);

    }

    public static class MyMapper extends Mapper<LongWritable, WebPermissionWritable, NullWritable, WebPermissionWritable> {
        @Override
        protected void map(LongWritable key, WebPermissionWritable value, Mapper<LongWritable, WebPermissionWritable, NullWritable, WebPermissionWritable>.Context context) throws IOException, InterruptedException {
            context.write(NullWritable.get(), value);
        }
    }
}
